package io.charstream;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

public class Test6 {
    public static void main(String[] args) throws IOException {
        /*String str = "abc\r\ndef\r\n\r\nghi";
        System.out.println(Arrays.toString(str.split("\r\n")));
        System.out.println(str.split("\r\n")[2]);*/
//        System.out.println("\r\n");
//        System.out.println(new Scanner(System.in).nextLine());

        registerUser();
    }

    private static boolean saveUser(String userName) {
        FileWriter fw = null;
        try {
            fw = new FileWriter("AdvancedCode/src/io/aaa/user.txt", Charset.forName("gbk"),true);
            fw.write("\r\n");
            fw.write(userName);
            fw.close();
            return true;
        } catch (Exception e) {
            return false;
        } finally {
            if (fw != null){
                try {
                    fw.close();
                } catch (IOException e) {
                    e.getStackTrace();
                }
            }
        }
    }

    private static void registerUser() throws IOException {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入用户名:");
        String user =  sc.nextLine();
        ArrayList<String> userList = getUserNames();
        if (!userList.contains(user)){
            System.out.println(saveUser(user) + "注册成功");
        } else {
            throw new IllegalArgumentException("用户名重复");
        }
    }

    private static ArrayList<String> getUserNames() throws IOException {
        FileReader br = new FileReader("AdvancedCode/src/io/aaa/user.txt", Charset.forName("gbk"));

        char[] chs = new char[1024];
        int ch;
        StringBuilder sb = new StringBuilder();
        while ((ch = br.read(chs)) != -1) {
            sb.append(chs, 0, ch);
        }
        ArrayList<String> list = new ArrayList<>(Arrays.asList(sb.toString().split("\r\n")));
        br.close();
        return list;
    }
}
